import axios from "axios";
import router from "../../router/index.js";
import {ElMessage} from "element-plus";

const TOKEN_KEY = 'Yang-ERP-jwt'

const request = axios.create({
    baseURL: '/api',
    timeout: 5000,
    headers: {
        'Content-Type': 'application/json;charset=UTF-8'
    }
})

// 请求拦截器
request.interceptors.request.use(
    config => {
        // 在发送请求之前做些什么，比如添加token
        const token = localStorage.getItem(TOKEN_KEY)
        if (token) {
            config.headers.Authorization = `Bearer ${token}`
        }
        return config
    },
    error => {
        // 对请求错误做些什么
        console.error(error)
        return Promise.reject(error)
    }
)

request.interceptors.response.use(
    response => {
        // HTTP 状态为 200，但后端可能用业务 code 表示失败
        if (response && response.status === 200) {
            if (response.data && response.data.code !== 200) {
                ElMessage.error(response.data.message || '操作失败')
                return Promise.reject(response.data)
            }
            return response.data
        }
        return response
    },
    error => {
        const {response} = error
        if (response) {
            if (response.status === 401) {
                localStorage.removeItem(TOKEN_KEY)
                ElMessage.error('未授权，请重新登录')
                router.push('/login')
            } else {
                // 其它 HTTP 错误统一提示
                const msg = (response.data && response.data.message) || `请求错误：${response.status}`
                ElMessage.error(msg)
            }
        } else {
            // 无 response，可能是网络错误或跨域阻断
            ElMessage.error('网络异常，请检查网络或稍后重试')
        }
        return Promise.reject(error)
    }
)

export default request
